package com.open.capacity.user.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysArea;
import com.open.capacity.user.service.SysAreaService;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.list.TreeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 区域管理
 */
@RestController
@Api(tags = "区域模块api")
public class SysAreaController {

    private static Logger logger = LoggerFactory.getLogger(SysAreaController.class);


    @Autowired
    private SysAreaService areaService;


    /**
     * 查询区域
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('area:get/areas')")
    @ApiOperation(value = "查询区域")
    @GetMapping("/areas")
    public Result<List<SysArea>> findAreas(@RequestParam Map<String, Object> params) {
        List<SysArea> list = areaService.findAreas(params);
        return Result.succeed(list);
    }

    /**
     * 查询区域tree
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('area:get/areas')")
    @ApiOperation(value = "查询区域tree")
    @GetMapping("/areas/tree")
    public Result<List<TreeVo>> treeAreas(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        List<SysArea> areas = areaService.findByParentId(parentId);
        List<TreeVo> treeList = new TreeList();
        areas.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getAreaName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId(m.getParentId());
            List<SysArea> childs = areaService.findByParentId(node.getId());
            node.setHasChildren(!CollectionUtils.isEmpty(childs));

            treeList.add(node);
        });

        return Result.succeed(treeList);
    }

    /**
     * 查询区域tree
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('area:get/areas')")
    @ApiOperation(value = "查询省市tree")
    @GetMapping("/areas/tree2")
    public Result<List<TreeVo>> treeAreas2(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        List<SysArea> areas = areaService.findByParentId(parentId);
        List<TreeVo> treeList = new TreeList();
        areas.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getAreaName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId(m.getParentId());
            if (m.getLayer() >= 2) {
                node.setHasChildren(false);
            } else {
                List<SysArea> childs = areaService.findByParentId(node.getId());
                node.setHasChildren(!CollectionUtils.isEmpty(childs));
            }

            treeList.add(node);
        });

        return Result.succeed(treeList);
    }



    /**
     * 查询区域list
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('area:get/areas')")
    @ApiOperation(value = "查询区域list")
    @GetMapping("/areas/list")
    public Result<List<SysArea>> listAreas(@RequestParam(value = "parentId", defaultValue = "0") String parentId, @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", parentId);
        params.put("keyword", keyword);
        List<SysArea> areas = areaService.findAreas(params);
        return Result.succeed(areas);
    }


    /**
     * 区域新增或者更新
     *
     * @param sysArea
     * @return
     */
    @PreAuthorize("hasAnyAuthority('area:post/areas','area:put/areas')")
    @ApiOperation(value = "保存区域")
    @PostMapping("/areas/saveOrUpdate")
    @LogAnnotation(module = "区域", name = "更新")
    public Result saveOrUpdate(@RequestBody SysArea sysArea, String keyValue) {
        return areaService.saveOrUpdate(sysArea, keyValue);
    }

    /**
     * 删除区域
     * delete /areas/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('area:delete/areas/{id}')")
    @ApiOperation(value = "删除区域")
    @DeleteMapping("/areas/{id}")
    @LogAnnotation(module = "区域", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            areaService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {

            return Result.failed("操作失败");
        }
    }

}
